window.Codes = {
    thisUrl:"./app/code/index.html",
    element:null,
    form:null,
    laypage:null,
    _baseUrl:'http://localhost:8888/',
    _getCodeTypeUrl:'w/code/types',
    _getCodeCategoryUrl:'w/code/categorys',
    _codeListUrl:'w/code/codeList',
    _saveCodeUrl:'w/code/saveCode',
    _viewCodeUrl:'w/code/viewCode',
    _renderSelect:function(type,category){
        Codes._ajaxGet(
            Codes._baseUrl+Codes._getCodeTypeUrl,{},
            function (result){
                if(result.status === "success"){
                    var data=result.data;
                    var $type=$("#type");
                    var $codeType=$("#codeType");
                    var _typeListLength=data.length;
                    var typeHtmlData="<option value=''></option>";
                    for(var i=0;i<_typeListLength;i++){
                        var _type=data[i];
                        typeHtmlData+="<option value='"+_type.typeName+"'>"+_type.typeName+"</option>"
                    }
                    $type.html(typeHtmlData);
                    $codeType.html(typeHtmlData);
                    Codes.form.render('select');
                    if (type){
                        Codes.form.val("form",{
                            "type": type
                        })
                    }
                }
            }, true
        );
        Codes._ajaxGet(
            Codes._baseUrl+Codes._getCodeCategoryUrl,{},
            function (result) {
                if(result.status === "success"){
                    var data=result.data;
                    var $category=$("#category");
                    var $codeCategory=$("#codeCategory");
                    var _categoryListLength=data.length;
                    var categoryHtmlData="<option value=''></option>";
                    for(var i=0;i<_categoryListLength;i++){
                        var _category=data[i];
                        categoryHtmlData+="<option value='"+_category.categoryName+"'>"+_category.categoryName+"</option>"
                    }
                    $category.html(categoryHtmlData);
                    $codeCategory.html(categoryHtmlData);
                    Codes.form.render('select');
                    if (category){
                        Codes.form.val("form",{
                            "category": category
                        })
                    }
                }
            }, true
        );
    },
    _renderContent:function(type,category,page){
        //获取数据
        Codes._ajaxGet(
            Codes._baseUrl+Codes._codeListUrl,
            {
                "type":type,
                "category":category,
                "isCreate":1,
                "isUser":0,
                "page":page,
                "size":5
            },
            function (result){
                if(result.status === "success"){
                    var data=result.data;
                    if(data){
                        var $codeList=$("#code-list-content");
                        var _codeListLength=data.length;
                        var codeListHtmlData="";
                        for(var i=0;i<_codeListLength;i++){
                            var _code=data[i];
                            codeListHtmlData+=
                                "<div class=\"code-abstract\">\n" +
                                "    <div class=\"code-abstract-title layui-row\">\n" +
                                "        <div class=\"user-avatar\">\n" +
                                "            <img class=\"avatar-image\" src=\"\" alt=\"潇洒的吸血鬼\">\n" +
                                "        </div>\n" +
                                "        <h3 class=\"title-name\">\n" +
                                "            <a onclick=\"Codes._viewCode("+_code.codeId+")\" href=\"javascript:;\">"+_code.codeAuthor+"&nbsp;&nbsp;/&nbsp;&nbsp;"+_code.codeAbstract+"</a>\n" +
                                "        </h3>\n" +
                                "        <div class=\"code-category\">\n" +
                                "            <span class=\"layui-badge layui-bg-gray\">"+_code.codeType+"</span>\n" +
                                "            <span class=\"layui-badge layui-bg-gray\">"+_code.codeCategory+"</span>\n" +
                                "        </div>\n" +
                                "    </div>\n" +
                                "    <div class=\"code-abstract-date layui-row\">\n" +
                                "        最后更新于\n" +
                                "        <span class=\"time-ago\">"+_code.lastEdit+"</span>\n" +
                                "    </div>\n" +
                                "</div>";

                        }
                        $codeList.html(codeListHtmlData);
                        var pageable=result.pageable;
                        var allPage=pageable.totalElements;
                        Codes._renderPageable(allPage);
                    }
                }
            }, true
        );
    },
    _renderPageable:function(allNum){
        $("#total").html("当前共有"+allNum+"个代码片段");
        Codes.laypage.render({
            elem:'pageable',
            count: allNum,//总页数
            limit:5,
            hash:"pageInfo",
            curr: location.hash.replace('#!pageInfo=', ''),
            prev: '<em>←</em>',
            next: '<em>→</em>',
            jump: function(obj,first){
                var category = $.getUrlParam('category');
                var type = $.getUrlParam('type');
                if(!first){
                    Codes._renderContent(type,category,obj.curr);
                }
            }
        });
    },
    _changeType:function(data){
        var category = $.getUrlParam('category');
        var newUrl = Codes.thisUrl+"?type="+encodeURI(data.value)+"&category="+category;
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.iframeSrc(index, newUrl);
    },
    _changeCategory:function(data){
        var type = $.getUrlParam('type');
        var newUrl = Codes.thisUrl+"?type="+type+"&category="+encodeURI(data.value);
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.iframeSrc(index, newUrl);
    },
    _createCode:function() {
        $("#list").css("display","none");
        $("#edit").css("display","block");
    },
    _saveCode:function(params){
        Codes._ajaxPost(
            Codes._baseUrl+Codes._saveCodeUrl,params,
            function (result){
                if(result.status === "success"){
                    location.reload(true);
                }
            }, true
        );
    },
    _editCode:function(){


    },
    _viewCode:function(codeId){
        Codes._ajaxGet(
            Codes._baseUrl+Codes._viewCodeUrl,
            {
                "codeId":codeId
            },
            function (result) {
                if(result.status === "success"){
                    var data=result.data;
                    //给Form赋值
                    Codes.form.val("codeView", {
                        "codeAbstract":data.codeAbstract,
                        "codeCategory":data.codeCategory,
                        "codeType":data.codeType,
                    });
                    $("#codeContentView").html("<code>"+data.codeContent+"</code>");
                    $('#codeContentView code').each(function(i, block) {
                        hljs.highlightBlock(block);
                    });
                    var $codeElement = $("code");
                    $codeElement.each(function(){
                        $(this).html("<ul><li>" + $(this).html().replace(/\n/g,"\n</li><li>") +"\n</li></ul>");
                    });
                    //打开弹出框
                    layer.open({
                        type: 1,
                        scrollbar: false,
                        area: ['60%', '60%'],
                        content: $("#codeView")
                    });
                }
            }, true
        );
    },
    _toList:function(){
        $("#list").css("display","block");
        $("#edit").css("display","none");
    },
    _init:function () {
        var category = $.getUrlParam('category');
        var type = $.getUrlParam('type');
        Codes._renderSelect(type,category);
        Codes._renderContent(type,category,1);
    },

    /*========================================================================*/
    /*下面是封装方法*/
    _ajaxRequest:function (type, url, data, callback, loading, cache) {
        var ajaxConfig = {
            url: '',
            data: {},
            callback: null,
            loading: true,
            cache: true,
            async: true
        };
        // 判断每一个参数url的类型
        // 如果是对象则是请求参数对象
        // 如果是字符串则是请求URL，参数和回调要继续检测后面的参数
        if (typeof url === 'string') {
            ajaxConfig.url = url;
            ajaxConfig.data = data;
            ajaxConfig.callback = callback;
            ajaxConfig.loading = typeof(loading) === 'undefined' ? true : loading;
            ajaxConfig.cache = cache;
        } else {
            ajaxConfig = $.extend({}, ajaxConfig, url);
        }
        var index = null;
        $.ajax({
            type: type,
            url: ajaxConfig.url,
            data: ajaxConfig.data,
            beforeSend: function() {
                if (ajaxConfig.loading) {
                    index = parent.layer.load(2, {time: 10*1000});
                }
            },
            dataType: 'json',
            cache: ajaxConfig.cache,
            async: ajaxConfig.async,
            traditional:true,
            success: function(result) {
                if (ajaxConfig.loading) {
                    parent.layer.close(index);
                }
                ajaxConfig.callback(result);
            },
            error: function(result) {
                if (ajaxConfig.loading) {
                    parent.layer.close(index);
                }
            }
        })
    },
    _ajaxGet:function (url, data, callback, loading) {
        Codes._ajaxRequest('GET', url, data, callback, loading, true);
    },
    _ajaxPost:function (url, data, callback, loading) {
        Codes._ajaxRequest('POST', url, data, callback, loading, false);
    }
};
$(function () {
    layui.use(['code','laypage','form','element'],function(){
        layui.code({
            about: false
        });
        var editor = ace.edit("codeContent");
        editor.setTheme("ace/theme/dreamweaver");
        editor.setOptions({
            enableBasicAutocompletion: true,
            enableSnippets: true,
            enableLiveAutocompletion: true
        });
        editor.setFontSize(15);
        editor.setOption("maxLines", 10);
        editor.setOption("minLines", 10);
        editor.renderer.setScrollMargin(0, 10, 10, 10);

        Codes.element = layui.element;
        Codes.form = layui.form;
        Codes.laypage = layui.laypage;

        Codes.form.on('select(category)', function(data){
            Codes._changeCategory(data);
        });
        Codes.form.on('select(type)', function(data){
            Codes._changeType(data);
        });
        Codes.form.on('submit(codeSubmit)', function(data){
            var params = data.field;
            if(params.hasOwnProperty('codePrivate')){
                params['codePrivate']=0
            }else{
                params['codePrivate']=1
            }
            var codeContent = editor.getValue();
            if(codeContent){
                params['codeContent']=codeContent;
                Codes._saveCode(params);
            }else{
                layer.msg("代码片段不可以为空",{icon:5,shift:6});
            }
        });
        Codes._init();
    });
});
